<?php
/************************************************************************
 Omnitrix - PHP Development Framework
 Copyright (C) 2012-2018 amonest(eastson@outlook.com)

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
************************************************************************/

class admin_controller_plugin extends omnitrix_controller
{
	public function index_action()
	{
		$rows = $this->_fetch_plugin_list();

		$list_table = otx_html_create_table($this->_('heading_index'), 'table-list');
		$list_table->set_head_cell($this->_('column_plugin_name'));
		$list_table->set_head_cell($this->_('column_plugin_status'), array('class' => 'center', 'width' => 150));
		$list_table->set_head_cell($this->_('column_installed_time'), array('class' => 'center', 'width' => 150));
		$list_table->set_head_cell($this->_('column_installed_user'), array('class' => 'center', 'width' => 150));
		$list_table->set_head_cell($this->_('text_actions'), array('class' => 'center', 'width' => 150));

		if ($rows) {
			foreach ($rows as $row) {
				$title = $row['title'];
				$description = empty($row['description']) ? '' : $row['description'];
				$website = empty($row['website']) ? '' : $row['website'];
				$email = empty($row['email']) ? '' : $row['email'];
				$author = empty($row['author']) ? $email : $row['author'];
				$version = empty($row['version']) ? '' : $row['version'];

				if ($website) {
					$plugin_detail = otx_html_strong(otx_html_link($title, array('href' => $row['website'], 'target' => '_blank')));
				} else {
					$plugin_detail = otx_html_strong($title);
				}

				if ($version) {
					$plugin_detail .= '&nbsp;(' . $version . ')';
				}

				if ($description) {
					$plugin_detail .= '<br />' . otx_html_small($description);
				}

				if ($author) {
					$plugin_detail .= '<br />'
							. otx_html_tag_start('i')
							. otx_html_tag_start('small')
							. $this->_('text_author');

					if ($email) {
						$plugin_detail .= otx_html_tag_simple('a', $author, array('href' => 'mailto:' . $email));
					} else {
						$plugin_detail .= $author;
					}

					$plugin_detail .= otx_html_tag_end('small')
							. otx_html_tag_end('i');
				}

				$actions = otx_html_tag_custom('dropdown');
				if (isset($row['plugin_id'])) {
					if ($row['plugin_status']) {
						$actions->add_item($this->_('action_deactivate'), otx_router_url('deactivate', null, null, array('id' => $row['plugin_id'])));
					} else {
						$actions->add_item($this->_('action_activate'), otx_router_url('activate', null, null, array('id' => $row['plugin_id'])));
					}
					$actions->add_item($this->_('action_uninstall'), otx_router_url('uninstall', null, null, array('id' => $row['plugin_id'])));
				} else {
					$actions->add_item($this->_('action_install'), otx_router_url('install', null, null, array('name' => $row['plugin_name'])));
				}

				$list_table->add_body_row();
				$list_table->set_body_cell($plugin_detail);
				$list_table->set_body_cell(isset($row['plugin_id']) ? ($row['plugin_status'] ? $this->_('text_active') : otx_html_strong($this->_('text_deactive'))) : otx_html_span($this->_('text_notinstalled'), array('class' => 'bold red')), array('class' => 'center'));
				$list_table->set_body_cell(isset($row['plugin_id']) ? otx_string_format_datetime($row['installed_time']) : '&nbsp;', array('class' => 'center'));
				$list_table->set_body_cell(isset($row['plugin_id']) ? otx_html_link($row['installed_user_name'], array('href' => otx_router_url('edit', 'user', 'admin', array('id' => $row['installed_user_id'])))) : '&nbsp;', array('class' => 'center'));
				$list_table->set_body_cell($actions->render_link($this->_('text_options')), array('class' => 'center actions'));
			};
		} else {
			$list_table->add_body_row();
			$list_table->set_body_cell($this->_('text_no_results'), array('colspan' => 5));
		}

		otx_html_add_navtab($this->_('navtab_index_title'), $this->_('navtab_index_desc', DIR_PLUGINS), otx_router_url('index'), true);
		otx_html_add_breadcrumb($this->_('breadcrumb_index'));
		otx_html_response_title($this->_('breadcrumb_index'));
	}

	public function install_action()
	{
		$plugin_name = otx_param_string('name');
		$plugin_instance = otx_plugin_instance($plugin_name);

		$row['plugin_name'] = $plugin_name;
		$row['plugin_status'] = 0;
		$row['installed_time'] = $GLOBALS['_XTIMESTAMP'];
		$row['installed_user_id'] = otx_session_user_id();
		otx_db_insert('#system_plugin#', $row);
		$row['plugin_id'] = otx_db_last_inserted_id();

		$plugin_instance->plugin_id = $row['plugin_id'];
		$plugin_instance->install();
		otx_event_dispatch('plugin_install', array('plugin_name' => $plugin_name));

		$plugin_instance->activate();
		otx_db_update('#system_plugin#', array('plugin_status' => 1), array('plugin_id' => $row['plugin_id']));
		otx_event_dispatch('plugin_activate', array('plugin_name' => $plugin_name));

		otx_cache_delete('plugins');

		$plugin_info = array_merge($row, otx_plugin_info($plugin_name));
		otx_admin_flash_message($this->_('text_success_install', $plugin_info));
		otx_admin_log_action($this->_('text_success_install', $plugin_info));
		otx_router_redirect('index');
	}

	public function uninstall_action()
	{
		$plugin_id = otx_param_int('id');

		$sql = 'SELECT * FROM #system_plugin# WHERE plugin_id = ?';
		$row = otx_db_fetch_row($sql, $plugin_id);
		if (false == $row) {
			otx_admin_flash_warning($this->_('error_invalid_id', $plugin_id));
			otx_router_redirect('index');
		}

		$plugin_instance = otx_plugin_instance($row['plugin_name']);

		if ($row['plugin_status']) {
			$plugin_instance->deactivate();
			otx_db_update('#system_plugin#', array('plugin_status' => 0), array('plugin_id' => $plugin_id));
			otx_event_dispatch('plugin_deactivate', array('plugin_name' => $row['plugin_name']));
		}

		$plugin_instance->uninstall();
		otx_db_delete('#system_plugin#',array('plugin_id' => $plugin_id));
		otx_event_dispatch('plugin_uninstall', array('plugin_name' => $row['plugin_name']));

		otx_cache_delete('plugins');

		$plugin_info = array_merge($row, otx_plugin_info($row['plugin_name']));
		otx_admin_flash_message($this->_('text_success_uninstall', $plugin_info));
		otx_admin_log_action($this->_('text_success_uninstall', $plugin_info));
		otx_router_redirect('index');
	}

	public function activate_action()
	{
		$plugin_id = otx_param_int('id');

		$sql = 'SELECT * FROM #system_plugin# WHERE plugin_id = ?';
		$row = otx_db_fetch_row($sql, $plugin_id);
		if (false == $row) {
			otx_admin_flash_warning($this->_('error_invalid_id', $plugin_id));
			otx_router_redirect('index');
		}

		$plugin_instance = otx_plugin_instance($row['plugin_name']);

		$plugin_instance->activate();
		otx_db_update('#system_plugin#', array('plugin_status' => 1), array('plugin_id' => $plugin_id));
		otx_event_dispatch('plugin_activate', array('plugin_name' => $row['plugin_name']));

		otx_cache_delete('plugins');

		$plugin_info = array_merge($row, otx_plugin_info($row['plugin_name']));
		otx_admin_flash_message($this->_('text_success_activate', $plugin_info));
		otx_admin_log_action($this->_('text_success_activate', $plugin_info));
		otx_router_redirect('index');
	}

	public function deactivate_action()
	{
		$plugin_id = otx_param_int('id');

		$sql = 'SELECT * FROM #system_plugin# WHERE plugin_id = ?';
		$row = otx_db_fetch_row($sql, $plugin_id);
		if (false == $row) {
			otx_admin_flash_warning($this->_('error_invalid_id', $plugin_id));
			otx_router_redirect('index');
		}

		$plugin_instance = otx_plugin_instance($row['plugin_name']);

		$plugin_instance->deactivate();
		otx_db_update('#system_plugin#', array('plugin_status' => 0), array('plugin_id' => $plugin_id));
		otx_event_dispatch('plugin_deactivate', array('plugin_name' => $row['plugin_name']));

		otx_cache_delete('plugins');

		$plugin_info = array_merge($row, otx_plugin_info($row['plugin_name']));
		otx_admin_flash_message($this->_('text_success_deactivate', $plugin_info));
		otx_admin_log_action($this->_('text_success_deactivate', $plugin_info));
		otx_router_redirect('index');
	}

	protected function _fetch_plugin_list()
	{
		$plugin_list = array();

		$sql = 'SELECT p.*, u.user_name AS installed_user_name
				FROM #system_plugin# p
				LEFT JOIN #system_user# u ON u.user_id = p.installed_user_id';
		$rows = otx_db_fetch_all($sql);
		if ($rows) {
			foreach ($rows as $row) {
				$plugin_info = otx_plugin_info($row['plugin_name']);
				$plugin_list[$row['plugin_name']] = array_merge($row, $plugin_info);
			}
		}

		$dirs = glob(DIR_PLUGINS . DS . '*');
		if ($dirs) {
			foreach ($dirs as $dir) {
				if (!is_dir($dir)) {
					continue;
				}

				$plugin_name = basename($dir);
				if (array_key_exists($plugin_name, $plugin_list)) {
					continue;
				}

				$plugin_info = otx_plugin_info($plugin_name);
				$plugin_info['plugin_name'] = $plugin_name;
				$plugin_list[$plugin_name] = $plugin_info;
			}
		}

		ksort($plugin_list);
		return $plugin_list;
	}
}